# -*- coding:utf-8 -*-
import webapp2
import jinja2
import gaesession
import random
from BiyiModel.RuobiyiBase import Product
from google.appengine.ext.db import Key
jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(''))
class Index(gaesession.BaseSessionHandler):
    def get(self):  
        store = int(self.request.get('store') or 0);
        category = int(self.request.get('category')  or 0);
    	products = Product.all();
        if store:
            products.filter('store =',store);
        if category:
            products.filter('category =',category);
    	products.order('-__key__');
    	items = [];
    	for p in products.run(limit=10):
    		items.append(p);
        temp = {'PageTitle': u'若比翼','products':items,'store':store,'category':category};
        template = jinja_environment.get_template('templates/home/index.html');
        self.response.out.write(template.render(temp));
    def list_products(self):
        lastid = int(self.request.get('lastid'));
        store = int(self.request.get('store') or 0);
        category = int(self.request.get('category')  or 0);
        products = Product.all();
        if store:
            products.filter('store =',store);
        if category:
            products.filter('category =',category);
        products.filter("__key__ < ", Key.from_path('Product',lastid));
        products.order('-__key__');
        items = [];
        for p in products.run(limit=10):
            item = {};
            item["id"] = p.key().id();
            item["title"] = p.title;
            item["image"] = p.image;
            item["clickurl"] = p.clickurl;
            item["description"] = p.description;
            item["store"] = p.store;
            item["category"] = p.category;
            items.append(item);
        self.ajaxReturn(0,'success',items);
routes = [
    webapp2.Route('/index', handler=Index, name='home'),
    webapp2.Route('/index/more', handler=Index, name='list', handler_method='list_products'),
    webapp2.Route('/', handler=Index, name='homedir'),
];
app = webapp2.WSGIApplication(routes,debug=True,config=gaesession.sessionconfig)
